package com.justgame.project.base.utils;

import com.justgame.project.cloud.base.entity.CurrentUser;
import com.justgame.project.cloud.base.entity.StringEncrypt;
import com.justgame.project.cloud.common.util.AppContextUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@SuppressWarnings("all")
public class JdbcTemplateUtils {
    public static JdbcTemplate getInstance(){
        return AppContextUtils.getBean(JdbcTemplate.class);
    }

    public static CurrentUser queryForAuthEntity(Long id){
        JdbcTemplate jdbcTemplate = getInstance();
        int[] argTypes = { java.sql.Types.INTEGER };
        Object[] args = { id };
        String sql = "SELECT id as `id`,user_name as `userName`,password as `password`,if(status = 'LOCKED',true,false) as `locked`, role as `role`" +
                "FROM sys_user_info where id = ? limit 1";
        return jdbcTemplate.queryForObject(sql, args, argTypes, new RowMapper<CurrentUser>() {
            @Override
            public CurrentUser mapRow(ResultSet resultSet, int i) throws SQLException {
                return CurrentUser.builder()
                        .id(resultSet.getLong(1))
                        .userName(resultSet.getString(2))
                        .password(StringEncrypt.encryptedOf(resultSet.getString(3)))
                        .locked(resultSet.getBoolean(4))
                        .role(resultSet.getString(5))
                        .build();
            }
        });
    }

    public static List<String> queryUserRoles(Long id){
        JdbcTemplate jdbcTemplate = getInstance();
        String sql = "SELECT role.`name` FROM sys_user_role_mapping roleMap " +
                "LEFT JOIN sys_role_info role on role.id = roleMap.role_id " +
                "WHERE roleMap.user_info_id = ? limit 1";
        return jdbcTemplate.queryForList(sql,new Object[]{id},String.class);
    }
}
